<?php
/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 */

class UserController extends Zend_Controller_Action
{
    private $_redirector = null;

    private $_userlist_page_limit = 30;
    
    public function init()
    {
        $this->_redirector = $this->_helper->getHelper('Redirector');
        $this->stylesBase  = $this->view->baseUrl() . '/styles/';
    }
    
    /**
     * This will validate our session and the requested action;
     */
    public function preDispatch()
    {
        // Check our identity
        if(Zend_Auth::getInstance()->hasIdentity())
        {
            // Check the requestion action
            switch ( $this->getRequest()->getActionName())
            {
                case 'login':
                case 'index':
                case 'ajaxrequest':
                case 'view':
                case 'editprofile':
                case 'logout':
                case 'register':
                case 'registrationuser':
                    // -- These actions are allowed, nothing to do -- //
                    break;
                default:
                    // -- Invalid action requested, refer to homepage -- //
                    $this->_helper->redirector('index', 'index');
                    break;
            }
        }
        else
        {
            // We have another layout for welcoming non-authenticated users
            $layout = $this->_helper->layout();
            $layout->setLayout('layout_index'); 
            
            // Check the requestion action
            switch($this->getRequest()->getActionName())
            {
                case 'logout':
                    $this->_helper->redirector('index');
                    break;
                default:
                    break;
            }
        }
    }
    
    /**
     * This action will handle all ajax-requests
     */
    public function ajaxrequestAction()
    {
        // Disable the layout
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        
        // Get current user
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        
        // These are default pager variables
        $current_page   = (int)$this->getRequest()->getParam('p');
        $pager_base     = $this->getRequest()->getBaseUrl()."/index/index/";
        
        // Get the request and do something accordingly
        $request  = (string)$this->getRequest()->getParam('req');
        switch($request)
        {
            case "pageusers":
                $pager_var      = "up";
                $html[]         = $this->_loopPartial('block-user', $this->_getAllUsers($current_page, $this->_userlist_page_limit));
                $html[]         = $this->_fetchPager($current_page, ($this->_countAllUsers()/$this->_userlist_page_limit), $pager_base, $pager_var);
                $result         = implode("\n", $html);
                break;
            default:
                $result = false;
                break;
        }
        
        // output result
        echo $result; 
    }

    /**
     * This is the main action.
     * It will display the My All-E page
     */
    public function indexAction()
    {
        // Set up the view
        $view   = $this->_getView('Userlist');
        // Get the logged in User-object, and get other 
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Pass some variables to our view
        $view->user     = $user;
        // Pager variables
        $pager_base     = $this->getRequest()->getBaseUrl()."/user/index/";
        // Set READINGLIST block
        $user_count         = $this->_countAllUsers();
        if($user_count > 0)
        {
            $user_pager_var     = "bp";
            $user_current_page  = (int)$this->getRequest()->getParam($user_pager_var);
            $user_current_page  = ($user_current_page > 0 ? $user_current_page : 1);
            $view->user_partial = $this->_loopPartial('block-user', $this->_getAllUsers($user_current_page, $this->_userlist_page_limit));
            $view->user_pager   = $this->_fetchPager($user_current_page, ($user_count/$this->_userlist_page_limit), $pager_base, $user_pager_var);
        }
        else
        {
            $view->user_partial = "<p>We did not find any users. Which is like totaly weird because you are reading this.</p>";
            $view->user_pager   = null;
        }
    }
    
    /**
     * Let's a user view a profile
     */
    public function viewAction()
    {
        // Set up the view
        $view   = $this->_getView('View user');
        // Get the logged in User-object, and get other 
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Pass some variables to our view
        $view->user     = $user;
        // Get the user ID we want to view
        $user_id        = (string)$this->getRequest()->getParam('id');
        if($user_id != null && strlen($user_id))
        {
            $view->profile  = $this->_getUserById($user_id);
        }
        else
        {
            // If there is no user id defined, we'll be viewing our own profile
            $view->profile  = $user;
        }
        //
        if($user->Id != $user_id)
        {
            // Message body content
            $view->message_title    = "Send message";
            $view->message_content  = $this->_addMessage();
        }
        else
        {
            // It's you! Let me show your messages
            
            // Maybe you need to see a specific message?
            $parent_id     = (string)$this->getRequest()->getParam('message');
            if(strlen($parent_id))
            {
                // Get the reply form
                $replyform  = $this->_replyMessage();
                // Get all messages for this PM
                $messages   = $this->_getMessagesByParentId($parent_id);
                // Get this message's user IDs
                $userIDs[]  = $messages[0]->Userfrom->Id;
                $userIDs[]  = $messages[0]->UserTo->Id;
                // We can only view this PM if we are either part of the conversation
                if(in_array($user->Id, $userIDs))
                {
                    // Mark this message as read
                    $readids    = $messages[0]->IsReadBy;
                    $readids[]  = $user->Id;
                    $this->_markMessageAsRead($parent_id, $readids);
                    
                    // Push data to the partial
                    $vars           = array(
                        'user'      => $user,
                        'parent_id' => $parent_id,
                        'subject'   => $messages[0]->Subject,
                        'messages'  => $this->_loopPartial('block-user-message-item', $messages, 0),
                        'form_add'  => $replyform,
                        'unread'    => $this->_getNumberOfUnreadMessagesByUserId($user->Id),
                    );
                    // Set our content
                    $view->viewmessage_content  = $view->partial('user/viewmessage.phtml', $vars);
                }
            }
            
            // Show your message list
            $vars           = array(
                'user'      => $user,
                'profile_id'=> $user_id,
                'messages'  => $this->_getMessagesByUserId($user->Id),
                'unread'    => $this->_getNumberOfUnreadMessagesByUserId($user->Id),
            );
            // Set our content
            $view->message_title    = "Your messages";
            $view->message_content  = $view->partial('partials/block-user-messages.phtml', $vars);
        }
        // Rewrite breadcrumb
        $page_user   = $view->navigation()->getContainer()->findOneByLabel('View profile');
        $page_user->setLabel($view->profile->Fullname)->setParams(array('id' => $view->profile->Id));
    }
    
    /**
     * Renders the loginform
     */
    public function loginAction()
    {
        $view = $this->_getView('Sign in');
        $view->form = $this->_getLoginForm();
    }
    
    /**
     * Handles logout
     */
    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        return $this->_helper->redirector('index', 'index');
    }
    
    /**
     * Let's a user register
     */
    public function registerAction()
    {
        // Get the view
        $view = $this->_getView('Register');
        // Get the form
        $form = $this->_getRegisterForm();
        // Handle post request
        if($this->getRequest()->isPost()) 
	{
            // Get the submitted data and validate it
            $formdata   = $this->_request->getPost();
            if($form->isValid($formdata)) 
            {
                // We can now safely store the data
                $mapper = new Application_Model_UserMapper();
                $values = $form->getValues();
                $user   = new Application_Model_User();
                
                $user->Givenname        = $values['user_givenname'];
                $user->Familyname       = $values['user_familyname'];
                $user->Password         = $values['user_password'];
                $user->Title            = $values['user_title'];
                $user->SecretQuestionId = $values['user_secretquestion_id'];
                $user->SecretAnswer     = $values['user_secretanswer'];
                $user->RoleId           = 2; // Set default to junior
         
                $user_id    = $mapper->save($user);
                
                if($user_id != null)
                {
                    // Store email(s)
                    $mapperUserHasEmail     = new Application_Model_UserHasEmailMapper();
                    $user_emails            = $mapperUserHasEmail->getEmailArrayFromUserEmail($values['user_primary_email'], $user_id);
                    $user_emails[0]->IsPrimary = 1;
                    if($mapperUserHasEmail->saveAll($user_emails))
                    {
                        /**
                         * User is registered -- log in
                         */
                        if($this->_authenticate(array('email' => $user_emails[0]->Email, 'password' => $values['user_password'])))
                        {
                            return $this->_helper->redirector('index', 'index');
                        }
                        
                        return $this->_helper->redirector('login', 'user');
                    }
                    else
                    {
                        die("Saving emails failed...");
                    }
                }
            }
        }
        
        $view->form = $form;
    }
    
    /**
     * Handles authorisation
     */
    public function authAction()
    {
        $request = $this->getRequest();
        $view = $this->_getView('Error - Sign in');
        $form = $this->_getLoginForm();

        // Validate form
        if(!$form->isValid( $request->getPost()))
        {
            $view->form = $form;
            return $this->render('login');
        }
        
        // Authenticate
        $values     = $form->getValues();                
        if(!$this->_authenticate($values))
        {
            $form->setDescription('Invalid username or password.');
            $view->form = $form;
            return $this->render('login');
        }
        
        // Redirect to index
        return $this->_helper->redirector('index', 'index');
    }
    
    /**
     * Let's a user edit his profile
     */
    public function editprofileAction()
    {
        // Get the view
        $view = $this->_getView('Edit Profile');
        // Get the form
        $form = $this->_getEditProfileForm();
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Breadcrumb
        $page_user   = $view->navigation()->getContainer()->findOneByLabel('View profile');
        $page_user->setLabel($user->Fullname)->setParams(array('id' => $user->Id));
        $page_user->addPage(array('label'=>'Edit profile', 'uri'=>$view->baseUrl().'/user/editprofile/'));
        // Handle post request
        if($this->getRequest()->isPost()) 
	{
            // Get the submitted data and validate it
            $formdata   = $this->_request->getPost();
            if($form->isValid($formdata)) 
            {
                // We must make sure that the user is updating his OWN profile
                if($user->Id == $formdata['user_id'])
                {
                    // We can now safely store the data
                    $mapper = new Application_Model_UserMapper();
                    $values = $form->getValues();
                    $user   = new Application_Model_User();

                    $user->Id               = $values['user_id'];
                    $user->Givenname        = $values['user_givenname'];
                    $user->Familyname       = $values['user_familyname'];
                    // Only update password if it's needed
                    if(strlen($values['user_password']))
                        $user->Password         = $values['user_password'];
                    $user->Title            = $values['user_title'];
                    $user->SecretQuestionId = $values['user_secretquestion_id'];
                    $user->SecretAnswer     = $values['user_secretanswer'];
                    $user->Dob              = $values['user_dob'];
                    $user->Addressline      = $values['user_addressline'];
                    $user->Postcode         = $values['user_postalcode'];
                    $user->City             = $values['user_city'];
                    $user->CountryId        = $values['user_country_id'];
                    $user->Bio              = $values['user_bio'];

                    // Update avatar if we must

                    $avatar_filename    = $form->user_avatar->getFileName();
                    if(strlen($avatar_filename))
                    {
                        $upload_location    = $avatar_filename;
                        $avatar_extension   = end(explode('.', $avatar_filename));
                        $avatar_location    = "assets/users/";
                        $avatar_savename    = 'user_'.$user->Id.'_avatar.'.$avatar_extension;
                        $avatar_savepath    = $avatar_location.$avatar_savename;

                        /**
                         * @todo    Handle fileuploads with Zend.
                         */
                        // Manually do the uploading and renaming, as the Zend way seems to fail
                        if(file_exists($avatar_location))
                        {
                            if(rename($upload_location, $avatar_savepath))
                                $user->Avatar   = $avatar_savename;
                        }
                    }

                    $user_id    = $mapper->save($user);

                    if($user_id != null)
                    {
                        // Store email(s)
                        $mapperUserHasEmail     = new Application_Model_UserHasEmailMapper();
                        $user_emails            = $mapperUserHasEmail->getEmailArrayFromUserEmail($values['user_primary_email'], $user_id);
                        if($mapperUserHasEmail->saveAll($user_emails))
                        {
                            // Update session
                            $this->_writeUserToStorage($user_id);
                            // Profile saved
                            return $this->_redirector->gotoSimple(
                                                   'view',
                                                   'user',
                                                   null,
                                                   array('id' => $user_id)
                            );
                        }
                        else
                        {
                            throw new Exception("Saving emails for user failed.");
                        }
                    }
                }
                else
                {
                    throw new Exception("Profile forgery detected: ".$user-Id." =/= ".$formdata['user_id']);
                }
            }
        }
        else
        {
            // Populate the form
            $form->populate(array(
                'user_id'               => $user->Id,
                'user_title'            => $user->Title,
                'user_givenname'        => $user->Givenname,
                'user_familyname'       => $user->Familyname,
                'user_primary_email'    => $user->PrimaryEmail->toFormValue(),
                'user_dob'              => $user->Dob,
                'user_bio'              => $user->Bio,
                'user_secretquestion_id'   => $user->SecretQuestionId,
                'user_secretanswer'     => $user->SecretAnswer,
                'user_addressline'      => $user->Addressline,
                'user_postalcode'       => $user->Postcode,
                'user_city'             => $user->City,
                'user_country_id'       => $user->CountryId,
            ));
        }
        
        $view->form = $form;
    }
    
    /**
     * This will display the reply to message form for a user
     */
    private function _replyMessage()
    {
        // Set our view
        $view = $this->view;
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Get the PM id we're replying too
        $pf_id  = (string)$this->getRequest()->getParam('id');
        $pm_id  = (string)$this->getRequest()->getParam('message');
        // Set up the form
        $form = $this->_getReplyMessageForm($pm_id, $pf_id);
        
        if ($this->getRequest()->isPost()) 
	{
            // Get the form data
            $formData  = $this->_request->getPost();
            // Prevent users from sending messages to themselves
            if($user->Id == $formData['users_user_to'])
            {
                // Easiest way to trigger an error
                $form->users_user_to->addValidators(array(
                    array('Regex', false, array('/[^0-9]/'))
                ))->addErrorMessage('You cannot send a message to yourself.');
            }
            // Validate form
            if ($form->isValid($formData)) 
            {
                // Save message
                if(($message_id = $this->saveMessageForm($form)) != null)
                {
                    // Reset form
                    $form->populate(
                        array(
                            'message_content' => "",
                        )
                    );
                }
            }
        }
        else
        {
            // We shall require some variables
            $pm_subject = "";
            // If we have a reply Id, we need to do a little bit of extra work
            if($pm_id != null)
            {
                // Get parent message
                $parent_message = $this->_getMessageById($pm_id);
                
                // Now we need to set some variables
                $pm_subject = "RE: ".$parent_message->Subject;
                $pm_to  = ($user->Id == $parent_message->Userfrom->Id ? $parent_message->Userto->Id : $parent_message->Userfrom->Id);
            }

            $form->populate(
                array(
                    'parent_id' => $pm_id,
                    'users_user_to' => $pm_to,
                    'message_subject' => $pm_subject,
                )
            );
        }
        
        return $form;
    }
    
    /**
     * Let's a user write a message
     */
    private function _addMessage()
    {
        // Set our view
        $view = $this->view;
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Next, we will need some request parameters
        $pm_to      = (string)$this->getRequest()->getParam('id');
        // Set up the form
        $form = $this->_getNewMessageForm($pm_to);
        // Request action
        if ($this->getRequest()->isPost()) 
	{
            // Get the form data
            $formData  = $this->_request->getPost();
            // We should be sending ourself a message
            if($user->Id == $formData['user_to_id'])
            {
                $form->users_user_to->setError('You cannot message yourself.');
            }
            // Validate form
            if ($form->isValid($formData)) 
            {
                // Save message
                if(($message_id = $this->saveMessageForm($form)) != null)
                {
                    // Redirect
                    $this->_redirector->gotoSimple(
                       'view',
                       'user',
                       null,
                       array(
                           'id' => $user->Id,
                           'message' => $message_id,
                       )
                    );
                }
            }
        }
        else
        {
            // Push data into our form
            $form->populate(
                array(
                    'users_user_to' => $pm_to,
                )
            );
        }
        
        return $form;
    }
    
    /**
     * Saves a message
     * @param $form The submitted form
     * @return integer $message_id
     */
    private function saveMessageForm($form)
    {
        // Get the values
        $values = $form->getValues();
        // Get the logged in User-object
        $user   = Zend_Auth::getInstance()->getStorage()->read();
        // Create our message
        $message = new Application_Model_Message();
        // Set only the interesting values
        if(strlen($values['parent_id']))
            $message->ParentId  = $values['parent_id'];
        $message->UserToId      = $values['users_user_to'];
        $message->UserFromId    = $user->Id;
        $message->Subject       = $values['message_subject'];
        $message->Content       = $values['message_content'];
        // Save the message
        $mapper     = new Application_Model_MessageMapper();                
        $message_id = $mapper->save($message);
        // Check if this message has a parent ID
        if($message_id != null && strlen($values['parent_id']))
        {
            $message_id = $values['parent_id'];
        }
        // Mark as read
        $this->_markMessageAsRead($message_id, $user->Id);
        
        return $message_id;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    

    


    public function detailsAction()
    {
        $view = $this->_getView('User details');
        
        $form = $this->_getDetailsForm();
        $form->getElement('user_search')->setJQueryParam('source', $view->baseUrl('user/search') );
        
        
        
        $request = $this->getRequest();
        // Formulier valideren
        if ( $request->isPost() ) {
            if ( $form->isValid( $request->getPost() ) ) {
                $userEmail = $form->getValue('user_email');      
                
                $users = $this->_findUsersByEmail($userEmail); 
                if(count($users)> 0)
                {
                    if($users[0]->Id != null)
                    {
                        $view->users = $users;
                    }
                }
            }
        }
        else
        {   
            $view->users = $this->_getAllUsers();
        }
        
        $view->headLink()->prependStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css');
        $view->form = $form;
    }

    public function searchAction()
    {
        $this->_helper->layout()->disableLayout(); // Layout uitschakelen
        $this->_helper->viewRenderer->setNoRender(true);
        
        $term   = $this->_getParam('term');
        $users  = $this->_findUsersByEmail($term);

        $result = array();
        foreach ($users as $user) {
            $result[] = $user->Fullname;
        }
        
        $this->_helper->json($result);        
    }

    public function editAction()
    {
        $view = $this->_getView('EditUser');
        $form = $this->_getEditUserForm();
        
        if ($this->getRequest()->isPost()) 
	{            
            $formData  = $this->_request->getPost();
                       
            if ($form->isValid($formData)) 
            {
                $view = $this->_getView('Fout - Toevoegen'); 
                
                // Get values
                $values = $form->getValues();
                
                // We need some Mappers
                $mprUserHasEmail    = new Application_Model_UserHasEmailMapper();
                $mprSecretQuestions = new Application_Model_SecretquestionMapper();
                $mprUser            = new Application_Model_UserMapper();
                
                // Set interesting values
                $user_values['id']              = $values['user_id'];
                $user_values['givenname']       = $values['user_givenname'];
                $user_values['familyname']      = $values['user_familyname'];
                $user_values['role']            = $values['user_role'];
                $user_values['active']          = $values['user_active'];
                $user_values['deleted']         = $values['user_deleted'];
                $user_values['prefnewsletter']  = $values['user_prefnewsletter'];
                $user_values['emails']          = $mprUserHasEmail->getEmailArrayFromUserEmail($values['user_emails']);
                $user_values['secretQuestion']  = $mprSecretQuestions->fetchById($values['user_secretquestion']);
                $user_values['secretAnswer']    = $values['user_secretanswer'];
                
                // Create our user
                $user       = new Application_Model_User($user_values);

                //Zend_Debug::dump($user);
                //die("bitch");

                // Save our user
                $mprUser->save($user);
                
                // let's redirect
                $this->_helper->redirector('details', 'user');            
            }
        }
        else
        {  
            $id = (string)$this->getRequest()->getParam('id');
            $user = $this->_getUser($id);

            // Only use the primary email
            if(count($user->Emails) > 0)
            {
                foreach($user->Emails as $UserEmail)
                {
                    if($UserEmail->IsPrimary)
                        break;
                }
            }

            //Zend_Debug::dump($UserEmail);
            //die("bitch");

            $form->populate(
                    array(
                        'user_id'               => $user->Id,    
                        'user_givenname'        => $user->Givenname,
                        'user_familyname'       => $user->Familyname,     
                        'user_emails'           => $UserEmail,
                        'user_secretquestion'   => $user->SecretQuestion,
                        'user_secretanswer'     => $user->SecretAnswer,
                        'user_role'             => $user->Role,
                        'user_bio'              => $user->Bio,
                    ));                                 
                              
            $view->user = $user;
        }
        
        $view->form = $form;  
    }

    /**
     * @return Application_Form_Registration
     *
     */
    private function _getDetailsForm()
    {
        return new Application_Form_Userdetails(array(
            'action' => $this->view->baseUrl('user/details'),
            'method' => 'post',
        ));
    }

    

    /**
     * @return Array
     *
     */
    private function _getUserByEmail($userEmail)
    {
        $userMapper = new Application_Model_UserMapper();        
        return $userMapper->fetchByEmail($userEmail); 
    }

    /**
     * @return Array
     *
     */
    private function _findUsersByEmail($email)
    {
        $userMapper = new Application_Model_UserMapper();        
        return $userMapper->findByEmail($email);
    }

    /**
     * @return Array
     *
     */
    private function _findUsersByName($name)
    {
        $userMapper = new Application_Model_UserMapper();        
        return $userMapper->findByName($name);
    }

    /**
     * @return Application_Form_EditUser
     *
     */
    private function _getEditUserForm()
    {
        return new Application_Form_EditUser(array(
            'action' => $this->view->baseUrl() . '/user/edit/',
            'method'   => 'post',
        ));
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /**
     * Get a user by ID
     * 
     * @param integer $user_id
     * @return Application_Model_User
     */
    private function _getUserById($user_id)
    {
        $mapper = new Application_Model_UserMapper();
        return $mapper->fetchById($user_id);
    }
    
    /**
     * Get all users
     * 
     * @param integer $page_nr      If you wish to use paging, pass the page-number. To
     *                              disable paging, pass null as value (default) and 
     *                              return all rows.
     * @param integer $nr_results   The number of results per page, defaults to 10.
     * @return Array(Application_Model_User)
     */
    private function _getAllUsers($page_nr = null, $nr_results = 0)
    {
        $mapper = new Application_Model_UserMapper();
        return $mapper->fetchAll($page_nr, $nr_results); 
    }
    
    /**
     * Returns the number of users
     * 
     * @return integer
     */
    private function _countAllUsers()
    {
        $mapper = new Application_Model_UserMapper();
        return $mapper->getCount();
    }
    
    /**
     * Get a message by its ID
     * 
     * @param integer $id
     * @return Application_Model_Message
     */
    private function _getMessageById($id)
    {
        $mapper = new Application_Model_MessageMapper();
        return $mapper->fetchById($id);
    }
    
    /**
     * Gets all messages for a user
     * @param integer $user_id
     * @return Array(Application_Model_Message)
     */
    private function _getMessagesByUserId($user_id)
    {
        $mapper = new Application_Model_MessageMapper();
        return $mapper->fetchByUserId($user_id);
    }
    
    /**
     * Get a message thread by its parent_id
     * @param integer $parent_id
     * @return Array(Application_Model_Message)
     */
    private function _getMessagesByParentId($parent_id)
    {
        $mapper = new Application_Model_MessageMapper();
        return $mapper->fetchByParentId($parent_id);
    }
    
    /**
     * Gets the number of unread messages for a user
     * @param integer $user_id
     * @return integer
     */
    private function _getNumberOfUnreadMessagesByUserId($user_id)
    {
        $mapper = new Application_Model_MessageMapper();
        return $mapper->fetchUnreadMessagesCountForUser($user_id);
    }
    
    /**
     * Returns the reply-to-message form
     * 
     * @return Application_Form_ReplyMessage
     */
    private function _getReplyMessageForm($reply_id, $user_id)
    {
        return new Application_Form_NewMessage(array(
            'action' => $this->view->baseUrl() . '/user/view/id/'.$user_id.'/message/'.$reply_id.'#viewmessage',
            'post'   => 'post',
        ));
    }
    
    /**
     * Returns the new-message form
     * 
     * @return Application_Form_ReplyMessage
     */
    private function _getNewMessageForm($user_id)
    {
        return new Application_Form_NewMessage(array(
            'action' => $this->view->baseUrl() . '/user/view/id/'.$user_id.'',
            'post'   => 'post',
        ));
    }
    
    /**
     * Mark a message as read
     * @param integer $parent_id
     * @param array $user_ids
     */
    private function _markMessageAsRead($parent_id, $user_ids)
    {
        $mapper = new Application_Model_MessageMapper();
        return $mapper->markAsRead($parent_id, (is_array($user_ids) ? $user_ids : array($user_ids)));
    }
    
    /**
     * Returns the login form
     * 
     * @return Application_Form_Login
     */
    private function _getLoginForm()
    {
        return new Application_Form_Login(array(
            'action' => $this->view->baseUrl() . '/user/auth',
            'method' => 'post',
        ));
    }

    /**
     * Returns the registration form
     * 
     * @return Application_Form_Register 
     */
    private function _getRegisterForm()
    {
        return new Application_Form_Register(array(
            'action' => $this->view->baseUrl() . '/user/register',
            'method' => 'post',
        ));
    }

    /**
     * Returns the edit profile form
     * 
     * @return Application_Form_EditProfile 
     */
    private function _getEditProfileForm()
    {
        return new Application_Form_EditProfile(array(
            'action' => $this->view->baseUrl() . '/user/editprofile',
            'method' => 'post',
        ));
    }
    
    /**
     * Authenticate a user
     */
    private function _authenticate($values)
    {
        $adapter    = $this->_getAuthAdapter($values);
        $auth       = Zend_Auth::getInstance();
        $result     = $auth->authenticate($adapter);
        if(!$result->isValid())
        {
            return false;
        }
        else
        {
            // Login
            $user       = null;
            $authrow    = $adapter->getResultRowObject();
            if($authrow != null)
                $this->_writeUserToStorage($authrow->user_id);
        }
        
        return true;
    }
    
    /**
     * Write the user to the storage
     * 
     * @param integer $user_id
     */
    private function _writeUserToStorage($user_id)
    {
        $auth       = Zend_Auth::getInstance();
        $user       = $this->_getUserById($user_id);
        $storage    = $auth->getStorage();
        $storage->write($user);
    }
    
    /**
     * @param array $values
     * @return Zend_Auth_Adapter_DbTable
     */
    private function _getAuthAdapter(array $values)
    {
        $authAdapter = new Ahs_Auth_Adapter_DbTable();
        $authAdapter->setIdentity($values['email'])
                    ->setCredential($values['password']);
        return $authAdapter;
    }

    /**
     * Loops through a list of custom objects, passing each object to the partial.
     * The end result is a html-render of the all the partials.
     *
     * @param string $partial
     * @param Array $objects
     * @return string
     */
    private function _loopPartial($partial, $objects, $extravars=null)
    {
        $result = array();
        $count  = 0;
        if(count($objects))
        {
            foreach($objects as $object)
            {
                $count++;
                $vars       = array(
                    'object'    => $object,
                    'count'     => $count,
                );
                
                if(is_array($extravars))
                    $vars = array_merge($extravars, $vars);
                
                $result[]   = $this->_getView("")->partial('partials/'.$partial.'.phtml', $vars);
            }
        }
        
        return implode("\n", $result);
    }

    /**
     * Get the HTML pager for a list that requires pagination
     *
     * @param int $page_nr
     * @param int $total_pages
     * @param string $base_url
     * @param string $page_var
     * @return string 
     */
    private function _fetchPager($current_page, $total_pages, $base_url, $page_var)
    {
        $view   = $this->_getView("");
        $vars   = array(
            'cur_page'      => $current_page,
            'nr_of_pages'   => ceil($total_pages),
            'base_url'      => $base_url,
            'page_var'      => $page_var,
        );
        
        return $view->partial('partials/pager.phtml', $vars);
    }

    /**
     * This returns the view for this controller.
     *
     * @param string $title
     * @return Zend_View
     */
    private function _getView($title)
    {
        $view = $this->view;
        $view->title = $title;
        $view->headTitle($view->title, 'PREPEND');

        return $view;
    }
}